const express = require("express");
const router = express.Router();
const pool = require("../pool.js");
const utils = require("../utils/index.js");
const myWxapi = require("../utils/wxapi.js");
const { body, validationResult, check } = require('express-validator');
const axios = require('axios');
var moment = require('moment');
const multer = require('multer');
const path = require('path');


// 配置上传文件存储位置和文件名
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads/')  // 上传的文件存储在 uploads 目录中
    },
    filename: function (req, file, cb) {
        // 使用当前时间戳和随机数作为上传后的文件名
        const uniqueSuffix = Date.now() + '_' + Math.round(Math.random() * 1E9);
        cb(null, uniqueSuffix + path.extname(file.originalname))
    }
});

// 创建 multer 实例
const upload = multer({ storage: storage, }); //50m limits: { fileSize: 50 * 1024 * 1024 } }); //50m


// const storage = multer.diskStorage({
//     destination: function (req, file, cb) {
//       cb(null, './uploads/')
//     },
//     filename: function (req, file, cb) {
//       const uniqueSuffix = Date.now()+ Math.round(Math.random() * 1E9)
//       cb(null, uniqueSuffix + path.extname(file.originalname))
//     }
//   })

// const upload = multer({ storage: storage })

// const upload = multer({ dest: './uploads/' });

router.post("/auth/login", async (req, res) => {
    //eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjEsImlhdCI6MTcwMzU5ODEyMiwiZXhwIjoxNzAzNjg0NTIyfQ.NuY1dcS05u1iHBaYiuiVfjqc1YAel-y1pONoJF645-I    
    let obj = req.body;
    let sql = "SELECT id,username FROM auth_user WHERE username=? AND password=?";
    console.log(obj.username, obj)
    pool.query(sql, [obj.username, obj.pwd], (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        if (result.length == 0) return res.send(utils.returnData({ code: -1, msg: "请输入正确的用户名和密码！", err, req }));
        let uid = result[0].id, admin = result[0].admin, name = obj.name;
        let token = utils.setToken({ uid });
        res.send(utils.returnData({ info: { uid, name, token, admin } }));
    });
});

//wx登录
// # 微信登录小程序
// # https://zhuanlan.zhihu.com/p/461863361
router.post("/auth/wx/login",
    [check('code')
        .notEmpty()
        .withMessage('code不能为空'),], async (req, res) => {
            console.log(1111)
            const validerrors = validationResult(req);
            if (!validerrors.isEmpty()) {
                let m = validerrors.errors[0].msg;
                return res.send(utils.returnData({ msg: m, info: validerrors.mapped() }));
            }

            let obj = req.body;
            console.log(obj);
            let data = await myWxapi.get_openid(obj.code);
            
            console.log(data);

            // 错误的code
            if (!data.openid) {
                return res.send(utils.returnData({ msg: data.errmsg }));
            } else {
                const openid = data.openid;
                let user = await utils.findBySql("select * from user where openid='" + openid + "'");
                console.log("select * from user where openid='" + openid + "'");
                console.log(user);
                let uid = 1;
                if (user && user.length > 0) {
                    console.log(2.5555);
                    let uid = user[0].id;
                    let token = utils.setToken({ uid });
                    console.log('token=' + token);
                    return res.send(utils.returnData({ info: { id: uid, name: user[0].username, token: token, grade: user[0].grade }, msg: '登陆成功' }));
                }else{
                    // 首次登录
                    console.log('首次登录');
                    let time = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
                    let sql = "insert into user (openid, username, avatarUrl, grade, create_time) values (?,?,?,?,?)";
                    pool.query(sql, [openid, obj.userInfo.nickName, obj.userInfo.avatarUrl, 1, time], (err, result) => {
                        // result:
                        // OkPacket {
                        //     fieldCount: 0,
                        //     affectedRows: 1,
                        //     insertId: 2,
                        //     serverStatus: 2,
                        //     warningCount: 0,
                        //     message: '',
                        //     protocol41: true,
                        //     changedRows: 0
                        // }

                        if (err || result.affectedRows <= 0) return res.send(utils.returnData({ code: -1, msg: '首次登录，注册失败，请联系管理员', err, req }));
                        // 生成token返回
                        uid = result.insertId;
                        let token = utils.setToken({ uid });
                        res.send(utils.returnData({ info: { id: result.insertId, name: openid, token: token }, msg: '登陆成功' }));
                    });
                }
                
            }

        });


// 获取当前登录用户资料
router.post('/user/profile', async (req, res) => {
    try {
        let user = await utils.getUserInfo(req, res);
        if (!user || !user.id) return; // getUserInfo 内部已返回错误
        let sql = "SELECT username, xm, email, dh, dw, grade FROM user WHERE id=?";
        pool.query(sql, [user.id], (err, result) => {
            if (err) return res.send(utils.returnData({ code: -1, err, req }));
            let info = result && result[0] ? result[0] : {};
            res.send(utils.returnData({ info }));
        });
    } catch (e) {
        res.send(utils.returnData({ code: -1, msg: '获取资料失败', req, err: e }));
    }
});

// 更新当前登录用户资料
router.post('/user/profile/update', async (req, res) => {
    try {
        let user = await utils.getUserInfo(req, res);
        if (!user || !user.id) return;
        let obj = req.body || {};
        let sql = "UPDATE user SET username=?, xm=?, email=?, dh=?, dw=?, grade=? WHERE id=?";
        console.log('obj.dw', obj.dw)
        pool.query(sql, [obj.username, obj.xm, obj.email, obj.dh, obj.dw, obj.grade, user.id], (err, result) => {
            if (err) return res.send(utils.returnData({ code: -1, err, req }));
            res.send(utils.returnData({ info: { updated: result.affectedRows > 0 } }));
        });
    } catch (e) {
        res.send(utils.returnData({ code: -1, msg: '更新资料失败', req, err: e }));
    }
});

// 搜索告警或故障信息
router.post("/jcs/list", async (req, res) => {

    // let sql = "select * from fault where info like concat('%', '" + message + "' ,'%')";
    let sql = "";
    

    sql = "SELECT alarm.name as info, jcs.jcs_name,jcs.id FROM alarm ,jcs,jcs_alarm where jcs_alarm.jcs_id = jcs.id and jcs_alarm.alarm_id = alarm.id "


    console.log(sql);
    pool.query(sql, async (err, result) => {
        // console.log(result);

        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        let mydata = [];
        for (let i = 0; i < result.length; i++) {
            // let myfaultsql = "select * from fault where alarm_id = " + result[i].id;
            // let fault = await utils.findBySql(myfaultsql);
            mydata[i] = result[i];
            // 根节点id
            mydata[i].rootid = result[i].id;
        }

        res.send(utils.returnData({ info: mydata }));
    });
    // }
});



// 搜索告警或故障信息
router.get("/search/fault", async (req, res) => {

    // id = req.params.id;

    let message ='%' + req.query.message + '%';
    let flag = req.query.flag;

    console.log('message', message, 'flag', flag);

    // let sql = "select * from fault where info like concat('%', '" + message + "' ,'%')";
    let sql = "";
    
    if(flag==0){
        sql = "SELECT alarm.name as info, jcs.jcs_name,jcs.id FROM alarm ,jcs,jcs_alarm where jcs_alarm.jcs_id = jcs.id and jcs_alarm.alarm_id = alarm.id and (alarm.name like ? or jcs.jcs_name like ?)"
    }else if(flag==1){
        sql = "SELECT fault.name as info, jcs.jcs_name,jcs.id FROM fault ,jcs,jcs_fault where jcs_fault.jcs_id = jcs.id and jcs_fault.fault_id = fault.id and (fault.name like ? or jcs.jcs_name like ?)"
    }else{
        ;
    }

    console.log(sql);
    pool.query(sql, [message, message],  async (err, result) => {
        // console.log(result);

        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        let mydata = [];
        for (let i = 0; i < result.length; i++) {
            // let myfaultsql = "select * from fault where alarm_id = " + result[i].id;
            // let fault = await utils.findBySql(myfaultsql);
            mydata[i] = result[i];
            // 根节点id
            mydata[i].rootid = result[i].id;
        }

        res.send(utils.returnData({ info: mydata }));
    });
    // }
});


// 通过id查询该节点信息
router.post("/getJcsNode", async (req, res) => {

    obj = req.body;

    let sql = "SELECT * from jcs where id=" + obj.id;

    let result = await utils.findBySql(sql);
    console.log('result', sql);
    if (result && result.length > 0) {
        // 查询图片列表
        let picsql = "SELECT * from images where jcs_id=" + result[0].id + " and is_del=0";
        // console.log(picsql);
        let piclist = await utils.findBySql(picsql);
        result[0].images = piclist;


        // 查询图片列表
        let nextsql = "SELECT id, node_text from jcs where parent_id=" + result[0].id;
        // console.log(picsql);
        let nextlist = await utils.findBySql(nextsql);

        if(nextlist && nextlist.length > 0){
            result[0].nextlist = nextlist;
        }else{
            result[0].nextlist = [];
        }
        res.send(utils.returnData({ info: result[0] }));
    }else{
        res.send(utils.returnData({ info: [] }));
    }
    
});




//获取用户信息
router.post("/getUserInfo", async (req, res) => {
    // let user = await utils.getUserRole(req, res);
    let user = await utils.getUserInfo(req, res);
    let sql = `SELECT b.menu_bg AS menuBg,b.menu_sub_bg AS menuSubBg,b.menu_text AS menuText,b.menu_active_text AS menuActiveText,b.menu_sub_active_text AS menuSubActiveText,b.menu_hover_bg AS menuHoverBg FROM theme AS b WHERE user_id=?`;
    pool.query(sql, [user.user.id], (err, result) => {
        if (err || result.length === 0) return res.send(utils.returnData({ code: -1, err, req }));
        res.send(utils.returnData({ info: { ...user, theme: result[0] } }));
    })

})


//查询设备
router.post("/getPartList", async (req, res) => {

    let obj = req.body;
    let {page,size}=utils.pageSize(obj.page,obj.size);
    let msg = obj.message || '';

    msg = '%' + msg + '%';
    // // 构建查询条件
    // let where = '';
    // const params = [];
    
    // if (name) {
    //   where = 'WHERE name LIKE ?';
    //   params.push(`%${name}%`);
    // }

    let { total } = await utils.getSum({ name: "parts", where: ``, res, req });
    // console.log(total);
    // let sql = `select * from xm`;
    // console.log(msg);
    let sql = "SELECT * from parts where name like ? or partNum like ?";
    pool.query(sql, [msg, msg], async (err, result) => {
        // console.log(result);
        if (err) return res.send(utils.returnData({ code: -1, err, req }));

        res.send(utils.returnData0({ data: result, total: total }));
    });
});


//查询知识管理
router.post("/getZsglList", async (req, res) => {

    let obj = req.body;
    let {page,size}=utils.pageSize(obj.page,obj.size);
    let msg = obj.message || '';

    msg = '%' + msg + '%';

    let { total } = await utils.getSum({ name: "zsgl", where: ``, res, req });
    // console.log(total);
    // let sql = `select * from xm`;
    // console.log(msg);
    let sql = "SELECT * from zsgl where name like ? or remark like ?";
    pool.query(sql, [msg, msg], async (err, result) => {
        // console.log(result);
        if (err) return res.send(utils.returnData({ code: -1, err, req }));

        res.send(utils.returnData0({ data: result, total: total }));
    });
});

module.exports = router;
